<template>
    <div class="company-autocomplete">
        <el-autocomplete clearable :size="size" v-model="searchKeyword" :fetch-suggestions="fetchSuggestions"
            placeholder="搜索公司名称" class="search-input" @select="handleSelect" @focus="handleFocus" @blur="handleBlur" />
    </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue';
import { getCompanyListApi } from '@/api/company';

let props = defineProps({
    size: {
        type: String,
        default: '',
    },
    modelValue: {
        required: true,
        type: Object,
    },
});

// 使用 ref 来统一管理搜索关键字
let searchKeyword = ref(props.modelValue?.name ?? '');
let previousValue = ref(props.modelValue?.name ?? '');

watchEffect(() => {
    searchKeyword.value = props.modelValue?.name ?? '';
    previousValue.value = props.modelValue?.name ?? '';
});

let emit = defineEmits(['update:modelValue', 'select']);

// 处理获取焦点事件
const handleFocus = () => {
    searchKeyword.value = '';
};

// 处理失去焦点事件
const handleBlur = () => {
    // 如果用户没有选择任何值，恢复到之前的值
    if (!searchKeyword.value || searchKeyword.value.trim() === '') {
        searchKeyword.value = previousValue.value;
        emit('update:modelValue', props.modelValue);
    }
};
// 搜索公司提示数据的方法
function fetchSuggestions(queryString, cb) {
    let name;
    if (searchKeyword.value.trim() === '' || !queryString) {
        name = null; // 传null表示查询所有公司
    } else {
        name = `%${queryString}%`; // 模糊查询，前后加%
    }
    
    const params = {
        name: name,
    };
    getCompanyListApi(params)
        .then((res) => {
            if (res.code === 200) {
                let suggestions =
                    res.data?.companies?.map((company) => {
                        return { value: company.name, id: company.id, ...company };
                    }) ?? [];
                cb(suggestions);
            } else {
                console.error(res.message);
                ElMessage.error(res.message);
            }
        })
        .catch((err) => {
            console.error(err);
            ElMessage.error(err.message || '获取公司列表失败');
        });
}

// 选择提示项后的回调方法
const handleSelect = (item) => {
    let { value, ...itemWithoutValue } = item;
    previousValue.value = value; // 更新之前的值
    emit('update:modelValue', itemWithoutValue);
    emit('select', itemWithoutValue);
};
</script>

<style scoped>
.company-autocomplete {
    max-width: 150px;
}

.search-input {
    width: 100%;
}
</style>